package com.swsc.solarverse.service.forward.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swsc.solarverse.common.util.ObjectMapper;
import com.swsc.solarverse.dao.entity.forward.ForwardEnvironmentalMonitorDataDO;
import com.swsc.solarverse.dao.mapper.forward.ForwardEnvironmentalMonitorDataMapper;
import com.swsc.solarverse.service.forward.IForwardEnvironmentalMonitorDataService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author AutoGenerator
 * @since 2022-08-24
 */
@Service
public class ForwardEnvironmentalMonitorDataServiceImpl extends ServiceImpl<ForwardEnvironmentalMonitorDataMapper, ForwardEnvironmentalMonitorDataDO> implements IForwardEnvironmentalMonitorDataService {

    @Override
    public void saveOrUpdateDos(List<ForwardEnvironmentalMonitorDataDO> dataDos) {
        if (CollectionUtils.isNotEmpty(dataDos)) {

            for (ForwardEnvironmentalMonitorDataDO dataDo : dataDos) {
                ForwardEnvironmentalMonitorDataDO rawDataDo = baseMapper.selectOne(Wrappers.lambdaQuery(ForwardEnvironmentalMonitorDataDO.class)
                        .eq(ForwardEnvironmentalMonitorDataDO::getTenantNo, dataDo.getTenantNo())
                        .eq(ForwardEnvironmentalMonitorDataDO::getOrganNo, dataDo.getOrganNo())
                        .eq(ForwardEnvironmentalMonitorDataDO::getDeviceId, dataDo.getDeviceId())
                        .orderByDesc(ForwardEnvironmentalMonitorDataDO::getDataTime)
                        .last("LIMIT 1")
                );
                if (null == rawDataDo) {
                    baseMapper.insert(dataDo);
                } else {
                    Integer id = rawDataDo.getId();
                    ObjectMapper.map(dataDo, rawDataDo);
                    rawDataDo.setId(id);
                    baseMapper.updateById(rawDataDo);
                }
            }
        }
    }

    @Override
    public void updateDos(List<ForwardEnvironmentalMonitorDataDO> dataDos) {
        if (CollectionUtils.isNotEmpty(dataDos)) {
            for (ForwardEnvironmentalMonitorDataDO dataDo : dataDos) {
                baseMapper.update(dataDo, Wrappers.lambdaUpdate(ForwardEnvironmentalMonitorDataDO.class)
                        .eq(ForwardEnvironmentalMonitorDataDO::getTenantNo, dataDo.getTenantNo())
                        .eq(ForwardEnvironmentalMonitorDataDO::getOrganNo, dataDo.getOrganNo())
                        .eq(ForwardEnvironmentalMonitorDataDO::getDeviceId, dataDo.getDeviceId())
                );
            }
        }
    }

    @Override
    public int insertOrUpdateBatch(List<ForwardEnvironmentalMonitorDataDO> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            return baseMapper.insertOrUpdateBatch(list);
        }
        return 0;
    }
}
